<script setup lang="tsx">
import type { VNode } from 'vue';
import { h, onMounted, ref } from 'vue';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';
import { featchGetDeptTree, fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusRecord, userGenderRecord } from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
import UserOperateDrawer from './modules/user-operate-drawer.vue';
import UserSearch from './modules/user-search.vue';

defineOptions({ name: 'UserManage' });

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetUserList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    status: undefined,
    username: undefined,
    // userGender: undefined,
    nick: undefined,
    phone: undefined,
    email: undefined
  },
  columns: () => [
    { type: 'selection', width: 48 },
    { prop: 'index', label: $t('common.index'), width: 64 },
    { prop: 'username', label: $t('page.manage.user.userName'), minWidth: 100 },
    // {
    //   prop: 'userGender',
    //   label: $t('page.manage.user.userGender'),
    //   width: 100,
    //   formatter: row => {
    //     if (row.userGender === undefined) {
    //       return '';
    //     }

    //     const tagMap: Record<Api.SystemManage.UserGender, UI.ThemeColor> = {
    //       1: 'primary',
    //       2: 'danger'
    //     };

    //     const label = $t(userGenderRecord[row.userGender]);

    //     return <ElTag type={tagMap[row.userGender]}>{label}</ElTag>;
    //   }
    // },
    { prop: 'nick', label: $t('page.manage.user.nickName'), minWidth: 100 },
    {
      prop: 'userPosition',
      label: $t('page.manage.user.userPosition'),
      align: 'left',
      minWidth: 300,
      formatter: row => {
        if (row.positionList !== undefined) {
          const positionList = row.positionList;
          const tags: VNode[] = [];
          // eslint-disable-next-line guard-for-in
          for (const i in positionList) {
            const rowTag: VNode[] = [];
            const position = positionList[i];
            rowTag.push(h(ElTag, { type: 'danger', effect: 'dark' }, position.cmpName));
            rowTag.push(h('span', ' | '));
            if (position.orgName) {
              rowTag.push(h(ElTag, { type: 'primary', effect: 'dark' }, position.orgName));
              rowTag.push(h('span', ' | '));
            }
            rowTag.push(h(ElTag, { type: 'success', effect: 'dark' }, position.positionName));
            tags.push(h('div', { style: { 'margin-bottom': '4px' } }, rowTag));
          }
          return h('div', { style: { 'margin-left': '10px' } }, tags);
        }
        return '';
      }
    },
    { prop: 'phone', label: $t('page.manage.user.userPhone'), width: 120 },
    // { prop: 'email', label: $t('page.manage.user.userEmail'), minWidth: 200 },
    {
      prop: 'status',
      label: $t('page.manage.user.userStatus'),
      align: 'center',
      formatter: row => {
        if (row.status === undefined) {
          return '';
        }

        const tagMap: Record<Api.Common.EnableStatus, UI.ThemeColor> = {
          '1': 'success',
          '0': 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <ElTag type={tagMap[row.status]}>{label}</ElTag>;
      }
    },
    {
      prop: 'operate',
      label: $t('common.operate'),
      align: 'center',
      width: 120,
      formatter: row => (
        <div class="flex-center">
          <ElButton type="primary" plain size="small" onClick={() => edit(row.id)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(row.id)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // eslint-disable-next-line no-console
  console.log(checkedRowKeys.value);
  // request

  onBatchDeleted();
}

function handleDelete(id: string) {
  // eslint-disable-next-line no-console
  console.log(id);
  // request

  onDeleted();
}

function edit(id: string) {
  handleEdit(id);
}

const orgData: any = ref([]);
onMounted(() => {
  featchGetDeptTree().then(res => {
    orgData.value = res.rows;
  });
});
const defaultProps = ref({
  label: 'name'
});
const currentNodeKey = ref(null);
</script>

<template>
  <ElContainer>
    <ElAside width="280px">
      <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <ElCard>
          <ElTree
            default-expand-all
            :data="orgData"
            :props="defaultProps"
            node-key="id"
            highlight-current
            empty-text="数据为空"
            class="h-280px"
            :expand-on-click-node="false"
            :current-node-key="currentNodeKey"
          />
        </ElCard>
      </div>
    </ElAside>
    <ElMain>
      <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
        <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
          <template #header>
            <div class="flex items-center justify-between">
              <p>{{ $t('page.manage.user.title') }}</p>
              <TableHeaderOperation
                v-model:columns="columnChecks"
                :disabled-delete="checkedRowKeys.length === 0"
                :loading="loading"
                @add="handleAdd"
                @delete="handleBatchDelete"
                @refresh="getData"
              />
            </div>
          </template>
          <div class="h-[calc(100%-50px)]">
            <ElTable
              v-loading="loading"
              height="100%"
              border
              class="sm:h-full"
              :data="data"
              row-key="id"
              @selection-change="checkedRowKeys = $event"
            >
              <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
            </ElTable>
          </div>
          <div class="mt-20px flex justify-end">
            <ElPagination
              v-if="mobilePagination.total"
              layout="total,prev,pager,next,sizes"
              v-bind="mobilePagination"
              @current-change="mobilePagination['current-change']"
              @size-change="mobilePagination['size-change']"
            />
          </div>
          <UserOperateDrawer
            v-model:visible="drawerVisible"
            :operate-type="operateType"
            :row-data="editingData"
            @submitted="getDataByPage"
          />
        </ElCard>
      </div>
    </ElMain>
  </ElContainer>
</template>

<style lang="scss" scoped>
:deep(.el-card) {
  .ht50 {
    height: calc(100% - 50px);
  }
}
</style>
